package com.eascs.ticket.schedule.scheduler;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.eascs.app.dao.PageResult;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.doc.template.TemplateHelper;
import com.eascs.common.util.DateUtils;
import com.eascs.common.util.StringUtil;
import com.eascs.ticket.common.component.MailNotifierComponent;
import com.eascs.ticket.config.ScheduleSetting;
import com.eascs.ticket.ticket.controller.TicketSearchComponent;
import com.eascs.ticket.ticket.form.TicketSearchForm;
import com.eascs.ticket.user.entity.User;
import com.eascs.ticket.user.service.UserService;

@Component
public class WarnTicketListEmailScheduler {
	private static Logger logger = LoggerFactory.getLogger(WarnTicketListEmailScheduler.class);

	@Inject
	private TicketSearchComponent ticketSearchComponent;

	@Inject
	private UserService userService;

	@Inject
	private MailNotifierComponent mailNotifierComponent;

	@Scheduled(cron = "0 0 8,13,16 * * ?")
	public void warnTicketListEmail() {
		logger.info("start warnTicketListEmail");
		TicketSearchForm ticketSearchForm = new TicketSearchForm();
		ticketSearchForm.setStatusNotIns("CLOSE;CANCEL");
		ticketSearchForm.setOrderBy("dueDate");
		ticketSearchForm.setPageSize(200);
		PageResult<Object[]> pageResult = ticketSearchComponent.searchTicket(ticketSearchForm);
		Date currentDate = DateUtils.truncateTime(new Date());
		Date nextDate = DateUtils.addDate(currentDate, 1);
		Map<String, List<Object[]>> ticketMap = new HashMap<>();
		for (int i = 0; i < pageResult.getData().size(); i++) {
			Object[] rowData = pageResult.getData().get(i);
			Date dueDate = getDueDate(rowData);
			if (nextDate.getTime() <= dueDate.getTime()) {
				break;
			}

			String operator = getOperator(rowData);
			List<Object[]> list = ticketMap.get(operator);
			if (null == list) {
				list = new ArrayList<Object[]>();
				ticketMap.put(operator, list);
			}
			list.add(rowData);
		}

		sendMail(ticketMap);
	}

	private void sendMail(Map<String, List<Object[]>> ticketMap) {
		logger.info("start sendMail");
		if (ticketMap.isEmpty())
			return;
		SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
		String nowDateStr = simpleDateFormat.format(new Date());
		Date currentDate = DateUtils.truncateTime(new Date());
		for (Map.Entry<String, List<Object[]>> entry : ticketMap.entrySet()) {
			String operator = entry.getKey();
			List<Object[]> tickets = entry.getValue();
			Map<String, Object> data = new HashMap<>();
			User user = userService.getUserByCode(operator);
			data.put("tickets", tickets);
			data.put("currentDate", currentDate);
			data.put("user", user);
			logger.info("TemplateHelper.process.operator={}", operator);
			String content = TemplateHelper.processClassPathTempate("/email/warnTicketListEmail.ftl", data);
			try {
				// 如果转交人和接收人是同一个人，则发送邮件
				// 新建邮件
				/** 标题 */
				String title = StringUtil.format("【工单系统】到期提醒:{}有{}个到期工单{}", user.getName(), tickets.size(), nowDateStr);
				/** 收件人 */
				if (!ScheduleSetting.getScheduleSetting().isMailEnable())
					return;
				String recipient = ScheduleSetting.getScheduleSetting().getMailRecipient();
				if (StringUtil.isBlank(recipient)) {
					recipient = user.getEmail();
					User supeior = userService.getSupeiorByUserCode(user.getCode());
					if (null != supeior) {
						recipient = recipient + "," + supeior.getEmail();
					}
					recipient = recipient + ",muwang.zheng@eascs.com";
				}
				logger.info("发送工单到期提醒operator={}", operator);
				mailNotifierComponent.notify(recipient, title, content, "WarnTicketListEmailScheduler");
			} catch (Exception e) {
				throw new RuntimeException(e.getMessage(), e);
			}

		}
	}

	private String getOperator(Object[] rowData) {
		return (String) rowData[23];
	}

	private Date getDueDate(Object[] rowData) {
		return (Date) rowData[7];
	}

}
